#!/home/kamal/work/iamalive/pythonenv/bin/python
# $Id: xtalk.py,v 1.2 2006/10/06 12:30:42 normanr Exp $
import sys,os,xmpp,time,select

class Bot:
	def __init__(self,jabber):
		self.jabber = jabber

	def register_handlers(self):
		self.jabber.RegisterHandler('message',self.xmpp_messageCB)
		self.jabber.RegisterHandler('presence',self.xmpp_presenceCB)

	def xmpp_messageCB(self, con, event):
		type=str(event.getType())
		fromjid=str(event.getFrom())
		#sys.stdout.write(fromjid)
		sys.stdout.write(fromjid + ' did some ' + type + ' activity with you\n')
		#if type in ['message', 'chat', None] and fromjid == self.remotejid:
		#	sys.stdout.write(event.getBody() + '\n')

	def xmpp_presenceCB(self,sess,presStanza):
		to=presStanza['to']
		if to:
			toJid=str(presStanza.getTo())
			sys.stdout.write('tojid is ' + toJid + '\n')

		fro=presStanza['from']
		if fro:
			fromJid=str(presStanza.getFrom())
			sys.stdout.write('fromJid is ' + fromJid + '\n')

		#jid=sess.peer
		#if jid:
		#	sys.stdout.write('peer jid is ' + jid + '\n')

		typ=presStanza.getType()
		if not typ or typ=='available':
			sys.stdout.write(' presence type is available\n')
			show=presStanza.getTag('show');
			if show:
				showData=presStanza.getTagData('show');
				sys.stdout.write('showData is ' + showData + '\n')

			status=presStanza.getTag('status')
			if status:
				statusData=presStanza.getTagData('status');
				sys.stdout.write('statusData is '+ statusData + '\n')

		elif typ=='unavailable' or typ=='error':
			sys.stdout.write('presence type is unavailable\n')
		elif typ=='probe':
				sys.stdout.write(' presence type is in probe mode\n')
		else:
				return
		#fromjid=str(pres.getFrom())
		#strPresenceType=str(pres.getType())
		#sys.stdout.write(fromjid)
		#sys.stdout.write(' did some activity \n')
		#sys.stdout.write(fromjid + ' is ' + strPresenceType + '\n')
		# TODO: LOG and also update the DB


	def stdio_message(self, message):
		m = xmpp.protocol.Message(to=self.remotejid,body=message,typ='chat')
		self.jabber.send(m)
		pass

	def xmpp_connect(self):
		print 'inside xmpp_connect; will call jabber.connect'
		con=self.jabber.connect(None, None, 0)
		print 'jabber.connect called'
		if not con:
			sys.stderr.write('could not connect!\n')
			return False

		sys.stderr.write('connected with %s\n'%con)
		auth=self.jabber.auth(jid.getNode(),jidparams['password'])
		if not auth:
			sys.stderr.write('could not authenticate!\n')
			return False
		sys.stderr.write('authenticated using %s\n'%auth)
		self.register_handlers()
		return con

if __name__ == '__main__':
	if len(sys.argv) < 2:
		print "Syntax: ImaPresenceTracker <conf_file_name>"
		sys.exit(0)
	
	#tojid=sys.argv[1]
	conffilename=sys.argv[1]
	
	jidparams={}
	if os.access(conffilename,os.R_OK):
		for ln in open(conffilename).readlines():
			if not ln[0] in ('#',';'):
				key,val=ln.strip().split('=',1)
				jidparams[key.lower()]=val

	for mandatory in ['jid','password']:
		if mandatory not in jidparams.keys():
			open(conffilename).write('#Uncomment fields before use and type in correct credentials.\n#JID=romeo@montague.net/resource (/resource is optional)\n#PASSWORD=juliet\n')
			print 'Please point ImaPresenceTracker config file to valid JID for tracking presence of the user.'
			sys.exit(0)
    
	jid=xmpp.protocol.JID(jidparams['jid'])
	cl=xmpp.Client(jid.getDomain(),debug=[])
	
	bot=Bot(cl)

	print 'Bot instance created'

	if not bot.xmpp_connect():
		sys.stderr.write("Could not connect to server, or password mismatch!\n")
		sys.exit(1)

	cl.sendInitPresence(requestRoster=0)   # you may need to uncomment this for old server
    
	socketlist = {cl.Connection._sock:'xmpp',sys.stdin:'stdio'}
	online = 1

	while online:
		(i , o, e) = select.select(socketlist.keys(),[],[],1)
		for each in i:
			if socketlist[each] == 'xmpp':
				cl.Process(1)
			elif socketlist[each] == 'stdio':
				msg = sys.stdin.readline().rstrip('\r\n')
				bot.stdio_message(msg)
			else:
				raise Exception("Unknown socket type: %s" % repr(socketlist[each]))

	#cl.disconnect()
